<template>
  <div class="index">
    <div id="he-plugin-simple"></div>
    <div style="background-size: 100% 100%;position:fixed;top:0;right:0;left:0;bottom:0;z-index: -1000;"
         :style="background.type !== 'iframe' ? {backgroundImage: `url(${background.imgurl ? background.imgurl : background.preview})`} : ''"></div>
    <iframe :src="background.src"
            v-if="background.type === 'iframe'"
            frameborder="0"
            scrolling="no"
            width="100%"
            height="100%"
            style="z-index:-1000;position: fixed;top:0;right:0;left:0;bottom: 0;"></iframe>
    <div class="circle-container">
      <div class="circle">
        <i class="open hidden" @click="close"></i>
        <i class="close" @click="open"></i>
      </div>
    </div>
    <div class="center">
      <div style="height: 100px;width: 230px;margin: auto;position: relative;">
        <template v-for="item in SEOptions"
        :key="item.id">
          <transition name="el-zoom-in-center">
            <a v-if="SELogo === item.id"
               :href="item.path"
               target="_blank">
                <img class="logo"
                     :src="item.logo"
                     alt="">
            </a>
          </transition>
        </template>
      </div>
      <div class="search">
        <el-input v-model="searchInput"
                  class="input-with-select"
                  autofocus
                  @input="searchChange"
                  @focus="searchChange"
                  :input-style="{color: lucency ? '#333333' : '#fff', fontSize: '16px',background: lucency ? '#fff' : 'transparent'}"
                  @keydown.enter="search">
          <template #prepend>
            <el-select v-model="SESelect" placeholder="Select" @change="selectSE" class="SE-select" :style="{color: lucency ? '#333333' : '#fff', fontSize: '16px',background: lucency ? '#fff' : 'transparent'}">
              <el-option v-for="item in SEOptions" :key="item.id" :label="item.label" :value="item.value" />
            </el-select>
          </template>
          <template #append>
            <el-button :style="{background:lucency ? '#fff' : 'transparent', height:'46px', width:'62px', borderRadius: '2px'}"
                       @click="search"
                       class="btn">
              <el-icon :color="lucency ? '#333' : '#fff'">
                <Search />
              </el-icon>
            </el-button>
          </template>
        </el-input>
        <div class="associate"
             v-show="showAssociate && searchInput && searchResult.length !== 0"
             :style="{background: lucency ? '#fff' : 'rgba(255, 255, 255, 0.2)'}">
          <TransitionGroup name="list" tag="ul">
            <el-button round
                       :style="{background: lucency ? '#409eff' : '#ffffff9b', color: lucency ? '#fff' : '#333333'}"
                       v-for="item in searchResult"
                       :key="item"
                       @click="search(item)"
                       class="assBtn">{{item}}</el-button>
          </TransitionGroup>
        </div>
      </div>
      <Grid :lucency="lucency" />
    </div>
    <div class="menu">
      <el-tooltip class="box-item"
                  :effect="lucency ? 'light' : 'dark'"
                  content="椰子鸡论坛"
                  placement="top">
        <el-button :color="lucency ? '#fff' : 'transparent'"
                   round
                   size="small"
                   :style="{border: lucency ? '1px solid #333' : '1px solid #fff'}"
                   class="btn"
                   @click="logger">
          <el-icon :color="lucency ? '#333  ' : '#fff'">
            <ChatLineSquare />
          </el-icon>
        </el-button>
      </el-tooltip>
      <el-tooltip class="box-item"
                  :effect="lucency ? 'light' : 'dark'"
                  content="Alone博客"
                  placement="top">
        <el-button :color="lucency ? '#fff' : 'transparent'"
                   round
                   size="small"
                   :style="{border: lucency ? '1px solid #333' : '1px solid #fff'}"
                   class="btn"
                   @click="blog">
          <el-icon :color="lucency ? '#333  ' : '#fff'">
            <Edit />
          </el-icon>
        </el-button>
      </el-tooltip>
      <el-tooltip class="box-item"
                  :effect="lucency ? 'light' : 'dark'"
                  content="背景切换"
                  placement="top">
        <el-button :color="lucency ? '#fff' : 'transparent'"
                   round
                   size="small"
                   :style="{border: lucency ? '1px solid #333' : '1px solid #fff'}"
                   class="btn"
                   @click="showBackground = true">
          <el-icon :color="lucency ? '#333  ' : '#fff'">
            <Picture />
          </el-icon>
        </el-button>
      </el-tooltip>
      <el-switch v-model="lucency"
                 inline-prompt
                 active-text="白底"
                 inactive-text="透明"
                 @change="lucencySwitch"
                 inactive-color="transparent"
                 style="margin-left:10px;">
      </el-switch>
    </div>
    <el-drawer v-model="showBackground"
               direction="ttb"
               size="100%"
               :before-close="handleClose"
               :z-index="100000">
      <Background @setBackground="setBackground" />
    </el-drawer>
    <!-- 工具箱展开按钮 -->
    <div :class="['utils-btn', 'animate__animated', 'animate__faster', utilsShow ? 'animate__fadeIn' : 'hidden', hidden ? 'hidden' : '']"
         @click="utilsClick">
      工具箱
    </div>

    <el-dialog v-model="utilsPopup">
      <el-scrollbar height="400px">
        <li v-for="(item, index) in toolsList"
            :key="index"
            class="infinite-list-item"
            @click="clickTools(item)">{{ item.title }}</li>
      </el-scrollbar>
    </el-dialog>
  </div>
  <el-drawer v-model="toolsDrawer"
             :title="drawerTitle"
             direction="ltr"
             size="50%"
             :before-close="toolsClose">
    <router-view />
  </el-drawer>
</template>

<script lang="ts">
import {
  defineComponent,
  ref,
  getCurrentInstance,
  ComponentInternalInstance,
  onMounted,
  reactive,
  watch,
} from "vue";
import { Search, Picture, Edit, ChatLineSquare } from "@element-plus/icons-vue";
import Background from "@/components/Background.vue";
import Grid from "@/components/Grid.vue";
import { ElMessage } from "element-plus";
import router from "@/router";
import { getSE } from '@/data/api'

export default defineComponent({
  components: {
    Search,
    Picture,
    Edit,
    ChatLineSquare,
    Background,
    Grid,
  },
  setup() {
    const { proxy } = getCurrentInstance() as ComponentInternalInstance;
    let that = proxy;
    const searchResult = ref([]);
    const showAssociate = ref(false);
    const searchInput = ref("");
    // 背景信息加载
    const background = reactive({
      name: null,
      preview: null,
      src: null,
      type: null,
      imgurl: null,
    });

    if (localStorage.getItem("background")) {
      if (
        JSON.parse(localStorage.getItem("background") as any).type === "api"
      ) {
        background.name = null;
        background.preview = null;
        background.src = null;
        background.type = null;
        background.imgurl = null;
        (proxy as any)
          .axios(JSON.parse(localStorage.getItem("background") as any).api)
          .then((res: any) => {
            (that as any).background = res.data;
            that.$forceUpdate();
          });
      } else {
        const obj = JSON.parse(localStorage.getItem("background") as any);
        background.name = obj.name;
        background.preview = obj.preview;
        background.src = obj.src;
        background.type = obj.type;
      }
    } else {
      background.name = "星空 10";
      background.preview =
        "https://636f-codenav-8grj8px727565176-1256524210.tcb.qcloud.la/covers/star/preview/cover_10.jpg";
      background.src =
        "https://636f-codenav-8grj8px727565176-1256524210.tcb.qcloud.la/covers/star/cover_10.jpg";
      background.type = "image";
    }

    const lucency = ref(false);
    const css_svg = ref("");
    // 是否透明主题
    if (localStorage.getItem("lucency") === "true") {
      lucency.value = true;
      css_svg.value = "#666666";
    } else {
      lucency.value = false;
      css_svg.value = "#ffffff";
    }

    const showBackground = ref(false);

    const lucencySwitch = () => {
      localStorage.setItem("lucency", String(lucency.value));
    };

    const handleClose = () => {
      showBackground.value = false;
    };

    const search = (e) => {
      if (searchInput.value !== "") {
        if (typeof e === "object") {
          window.open(searchUrl + searchInput.value);
        } else {
          window.open(searchUrl + e);
        }
        showAssociate.value = false;
        searchResult.value = [];
      } else {
        ElMessage({
          message: "请输入内容再点击搜索!",
          type: "error",
          center: true,
          grouping: true,
        });
      }
    };

    const onClose = () => {
      showAssociate.value = false;
    };

    const blur = (event) => {
      const className = event.target.className;
      if (
        className !== "associate" &&
        className !== "el-input__inner" &&
        className !== "el-button el-button--default is-round" &&
        className !== ""
      ) {
        onClose();
      } else {
        showAssociate.value = true;
      }
    };

    const logger = () => {
      window.open("http://yeziji.xyz/logger");
    };

    const blog = () => {
      window.open("https://blog.a3-507.top/");
    };

    const setBackground = (e) => {
      showBackground.value = false;
      background.name = null;
      background.preview = null;
      background.src = null;
      background.type = null;
      background.imgurl = null;
      localStorage.setItem("background", JSON.stringify(e));
      if (e.type === "api") {
        proxy.axios(e.api).then((res) => {
          background.imgurl = res.data.imgurl;
          background.type = "image";
          that.$forceUpdate();
        });
      } else {
        background.name = e.name;
        background.preview = e.preview;
        background.src = e.src;
        background.type = e.type;
        that.$forceUpdate();
      }
    };

    const searchChange = () => {
      if (searchInput.value !== "" && !searchInput.value.match(/^[ ]*$/)) {
        proxy
          .axios(
            `/5a1Fazu8AA54nxGko9WTAnF6hhy/su?json=1&wd=${searchInput.value}`
          )
          .then((res) => {
            showAssociate.value = true;
            searchResult.value = [];
            searchResult.value = JSON.parse(
              res.data.match(/(?<=.*\()(.*)(?=\);)/)[0]
            ).s;
            that.$forceUpdate();
          });
      } else {
        showAssociate.value = false;
      }
    };
    const offsetHeight = ref(document.documentElement.offsetHeight);
    const utilsShow = ref(false);
    const hidden = ref(false);
    const move = (e) => {
      const x = e.clientX;
      const y = e.clientY;
      const btnTop = offsetHeight.value * 0.5 - 100;
      const btnBottom = offsetHeight.value * 0.5 + 100;
      if (x <= 50 && y >= btnTop && y <= btnBottom) {
        if (!utilsShow.value) {
          utilsShow.value = true;
          hidden.value = false;
        }
      } else {
        if (utilsShow.value) {
          utilsShow.value = false;
          hidden.value = true;
        }
      }
    };
    const utilsPopup = ref(false);
    const utilsClick = () => {
      utilsPopup.value = true;
    };

    const toolsList = [
      { title: "在线发邮件", path: "email" },
      { title: "短网址生成", path: "shortUrl" },
    ];
    const toolsDrawer = ref(false);
    const drawerTitle = ref("");
    const clickTools = (e) => {
      router.push(e.path);
      drawerTitle.value = e.title;
      toolsDrawer.value = true;
    };

    const toolsClose = () => {
      router.push("/");
      toolsDrawer.value = false;
    };
    const path = router.currentRoute.value.path;
    if (path === "/email") {
      drawerTitle.value = "在线发邮件";
      toolsDrawer.value = true;
    } else if (path === "/shortUrl") {
      drawerTitle.value = "短网址生成";
      toolsDrawer.value = true;
    }

    onMounted(() => {
      (window as any).WIDGET = {
        CONFIG: {
          modules: "01234",
          background: "5",
          tmpColor: "D9D9D9",
          tmpSize: "16",
          cityColor: "D9D9D9",
          citySize: "16",
          aqiColor: "D9D9D9",
          aqiSize: "16",
          weatherIconSize: "24",
          alertIconSize: "18",
          padding: "10px 10px 10px 10px",
          shadow: "0",
          language: "auto",
          borderRadius: "5",
          fixed: "true",
          vertical: "top",
          horizontal: "right",
          right: "10",
          top: "10",
          key: "d97d22107d5443a898aaa91421719b06",
        },
      };
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src =
        "https://widget.qweather.net/simple/static/js/he-simple-common.js?v=2.0";
      document.getElementsByTagName("head")[0].appendChild(script);
    });
    watch(lucency, (news) => {
      if (news) {
        css_svg.value = "#666666";
      } else {
        css_svg.value = "#ffffff";
      }
    });

    var SE = JSON.parse(localStorage.getItem('SE'));
    const SESelect = ref(SE ? SE.value : 'baidu')
    const SELogo = ref(SE ? SE.id : 1)
    const SEOptions = ref([])
    let searchUrl = SE ? SE.search_path : 'https://www.baidu.com/s?wd='

    getSE().then(res => {
      if (res.code === 200) {
        SEOptions.value = res.data
      }
    })

    const selectSE = (SE) => {
      SEOptions.value.forEach(item => {
        if (item.value === SE) {
          SELogo.value = item.id
          searchUrl = item.search_path
          localStorage.setItem('SE', JSON.stringify(item))
        }
      })
    }
    return {
      searchInput,
      background,
      lucency,
      showBackground,
      searchResult,
      showAssociate,
      lucencySwitch,
      handleClose,
      search,
      onClose,
      blur,
      logger,
      blog,
      setBackground,
      searchChange,
      move,
      utilsClick,
      clickTools,
      toolsClose,
      drawerTitle,
      toolsDrawer,
      utilsPopup,
      utilsShow,
      hidden,
      toolsList,
      css_svg,
      css_bgc: lucency.value ? '#ffffff' : 'transparent',
      SESelect,
      SEOptions,
      selectSE,
      SELogo
    };
  },
});
</script>

<style lang="less">
.index {
  z-index: -1000;
  #he-plugin-simple {
    z-index: 100000;
  }
  div {
  }
  iframe {
  }
  .center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    @media screen and (max-width: 800px) {
      top: 50%;
      left: 20%;
      transform: translate(-10%, -50%);
    }
    a {
      .logo {
        position: absolute;
        left: 0;
        width: 210px;
        height: 80%;
        background-color: rgba(0, 0, 0, 0.05);
        padding: 10px 30px;
        border-radius: 10px;
        //@media only screen and (max-width: 800px) {
        //  width: 26%;
        //}
        &:hover {
          opacity: 0.7;
        }
      }
    }
    .search {
      margin: 20px auto 0;
      width: 638px;
      position: relative;
      z-index: 1000;
      @media only screen and (max-width: 800px) {
        width: 92%;
      }
      .input-with-select {
        height: 47px;
        border-radius: 5px;
        background: transparent;
        .btn {
          &:hover {
            background-color: #409eff;
          }
        }
      }
      .associate {
        background-color: #fff;
        position: absolute;
        top: 47.5px;
        z-index: 1000;
        border-bottom-left-radius: 5px;
        border-bottom-right-radius: 5px;
        display: flex;
        flex-wrap: wrap;
        padding: 5px;
        box-sizing: border-box;
        box-shadow: 0 0 5px #999999;
        width: 575px;
        overflow: hidden;
        @media only screen and (max-width: 800px) {
          width: calc(100% - 62px);
        }
        .el-button {
          margin: 5px;
          &:hover {
            opacity: 0.7;
          }
        }
      }
      .el-icon,
      .icon {
        color: v-bind(css_svg);
        height: 20px;
        width: 20px;
        position: relative;
        top: 0.5px;
      }
    }
  }
  .menu {
    position: fixed;
    bottom: 16px;
    right: 16px;
    display: flex;
    align-items: center;
    .el-button {
      margin-left: 10px;
      padding: 0 13px;
      &:hover {
        opacity: 0.7;
      }
    }
    .el-switch {
      &:hover {
        opacity: 0.7;
      }
    }
  }
  .utils-btn {
    width: 23px;
    height: 70px;
    position: fixed;
    left: 0;
    top: 50%;
    transform: translate(0, -50%);
    background-image: linear-gradient(
      darken(#f3f3f3, 0%),
      darken(#f3f3f3, 30%)
    );
    opacity: 0.8;
    display: flex;
    align-items: center;
    border-top-right-radius: 10px;
    border-bottom-right-radius: 10px;
    font-size: 12px;
    cursor: pointer;
  }
  .hidden {
    display: none;
  }
  .infinite-list-item {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 50px;
    background: var(--el-color-primary-light-9);
    color: var(--el-color-primary);
    margin: 10px;
    cursor: pointer;
    &:hover {
      opacity: 0.7;
    }
  }

  .el-drawer {
    z-index: 100000;
    background: transparent;
    position: relative;
  }
}
.el-drawer__header {
  span {
    font-size: 30px;
    @media only screen and (max-width: 800px) {
      font-size: 24px;
    }
  }
}
.el-input__inner {
  height: 47px;
  width: 100%;
  @media only screen and (max-width: 800px) {
    width: 100%;
  }
  &:hover {
    border-color: #409eff;
  }
}
.el-input-group__append {
  background: transparent;
  .icon {
    color: v-bind(css_svg);
  }
  &:hover {
    border-color: #409eff;
    .icon {
      color: #409eff;
    }
  }
}
.el-drawer__close-btn {
  z-index: 10000;
}
.el-badge,
.el-message_badge {
  display: none;
}
.el-input-group__prepend {
  background: v-bind(css_bgc);
}
.el-input__suffix-inner {
  display: flex;
  align-items: center;
}
.SE-select {
  width: 130px;
  @media screen and (max-width: 800px) {
    width: 80px;
  }
}

.list-enter-active {
  transition: all 0.6s ease;
}
.list-leave-active {
  transition: all 0s ease;
}
.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
</style>
